using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UwinEducation.Domain.Entities;
using UwinEducation.Domain.IRepositories;
using UwinEducation.Infrastructure.Persistence;

namespace UwinEducation.Infrastructure.Repositories
{
    /// <summary>
    /// 系统配置仓储实现
    /// </summary>
    public class SystemConfigRepository : Repository<SystemConfig, Guid>, ISystemConfigRepository
    {
        public SystemConfigRepository(ApplicationDbContext context) : base(context)
        {
        }

        /// <inheritdoc/>
        public async Task<SystemConfig> GetByKeyAsync(string key)
        {
            return await BaseQuery().FirstOrDefaultAsync(x => x.Key == key);
        }

        /// <inheritdoc/>
        public async Task<string> GetValueByKeyAsync(string key)
        {
            var config = await GetByKeyAsync(key);
            return config?.Value;
        }

        /// <inheritdoc/>
        public async Task<bool> UpdateValueAsync(string key, string value)
        {
            var config = await GetByKeyAsync(key);
            if (config == null)
            {
                // 创建新配置
                config = SystemConfig.Create(
                    key: key,
                    value: value,
                    description: string.Empty
                    );
                await AddAsync(config);
            }
            else
            {
                config.Value = value;
                config.UpdatedAt = DateTime.Now;

                await UpdateAsync(config);

            }
            return true;
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<SystemConfig>> GetAllAsync()
        {
            return await BaseQuery().ToListAsync();
        }



        
    }
}